//
//  ZPBackPasswordViewController.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/12/2.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPChangePwdViewController.h"
#import "ZPBackSetPwdViewController.h"
#import "ZPUpdateSetPwdViewController.h"

@interface ZPChangePwdViewController ()
{
    MBProgressHUD *hud;
}
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumLab;

@property (weak, nonatomic) IBOutlet UIButton    *getVerificationCode;
@property (weak, nonatomic) IBOutlet UITextField *verificationCode;
@property (weak, nonatomic) IBOutlet UIButton    *nextStepBtn;

@property (strong, nonatomic) ZPCallAlertView *callAlertView;
@end

@implementation  ZPChangePwdViewController
#pragma mark - <视图加载完成viewDidLoad>
- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    self.title=@"修改密码";
//    switch (_inType) {
//        case 0:{
//            self.title=@"修改密码";
//            self.phoneNumLab.hidden=NO;
//            self.phoneNumTF.hidden=YES;
//        }
//            break;
//        case 1:{
//            self.title=@"找回密码";
//            self.phoneNumLab.hidden=YES;
//            self.phoneNumTF.hidden=NO;
//        }
//            break;
//    }
    
    NSString *tempStr = [[ZPAuthStore sharedZPAuthStore].userToDic objectForKey:@"mobile"];
    
    if (self.flag == 100) {
        self.title = @"找回密码";
        self.phoneNumLab.hidden=YES;
        self.phoneNumTF.hidden=NO;
    }
    else if(self.flag == 101) {
        self.title = @"修改密码";
        self.phoneNumLab.hidden=NO;
        self.phoneNumTF.hidden=YES;
        self.phoneNumTF.text = tempStr;
    }

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(textFieldDidChanged) name:UITextFieldTextDidChangeNotification object:nil];

    // 登录状态获取手机 截密处理
    if (tempStr.length > 7) {
        for (int i = 0; i < tempStr.length; i++) {
            if (i > 2 && i < tempStr.length - 4) {
                tempStr = [tempStr  stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
            }
        }
        self.phoneNumLab.text = tempStr;
    }else {
        self.phoneNumLab.text = tempStr;
    }

}


- (void)dismissKeyboard
{
    [self.phoneNumTF resignFirstResponder];
    [self.verificationCode resignFirstResponder];
}

- (void)textFieldDidChanged
{
    if ( self.verificationCode.text.length !=0) {
        self.nextStepBtn.enabled = YES;
        self.nextStepBtn.backgroundColor = zMainColor;
    } else {
        self.nextStepBtn.enabled = NO;
        self.nextStepBtn.backgroundColor = zFreeColor(204, 204, 204, 1);
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
        [self.navigationController setNavigationBarHidden:NO];
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:Z_IMAGE(@"zhenpin_back") forState:UIControlStateNormal];
    leftBtn.frame= CGRectMake(0, 0, 26, 26);
    [leftBtn addTarget:self action:@selector(clickBackButtonItem) forControlEvents:UIControlEventTouchUpInside];
    
    //  self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_close"] style:UIBarButtonItemStylePlain target:self action:@selector(clickBackButtonItem)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
}
- (void)clickBackButtonItem
{
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CountDownP:) name:[NSString stringWithFormat:@"%@P",NSStringFromClass([self class])] object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CountDownS:) name:[NSString stringWithFormat:@"%@S",NSStringFromClass([self class])] object:nil];
}



-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:[NSString stringWithFormat:@"%@P",NSStringFromClass([self class])] object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:[NSString stringWithFormat:@"%@S",NSStringFromClass([self class])] object:nil];
    [super viewDidDisappear:animated];
}

-(void)CountDownP:(NSNotification *)not{
    NSString *strTime = [NSString stringWithFormat:@"%@秒后重发",[not.userInfo objectForKey:@"time"]];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.getVerificationCode.titleLabel.text = strTime;
        [self.getVerificationCode setTitle:strTime forState:UIControlStateNormal];
        [self.getVerificationCode setTitle:strTime forState:UIControlStateDisabled];
        self.getVerificationCode.enabled = NO;
        self.getVerificationCode.backgroundColor = zFreeColor(209, 209, 209, 1);
    });
}

-(void)CountDownS:(NSNotification *)not{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.getVerificationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.getVerificationCode.enabled = YES;
        self.getVerificationCode.backgroundColor = zMainColor;
    });
}




#pragma mark - <获取验证码>
- (IBAction)getVerifiCode:(UIButton *)sender
{
    NSString *mobileNum = self.phoneNumTF.text;
    
    if ([mobileNum length] > 0 )
    {
        if ([mobileNum zp_isValidPhoneNum])
        {
        
            NSDictionary *params = @{@"mobile": mobileNum,
                                     @"type":@"1"};
            [[ZPNetworking sharedZPNetworking] POST:APIPPT@"access/getValidateCode.json" parameters:params progress:^(NSProgress * _Nullable progress) {
                
            } success:^(id  _Nonnull responseObject) {
                if ([[responseObject objectForKey:@"code"] integerValue]==200) {
                    [ZPPromptView showMessage:@"验证码发送成功"];
                }
                else {
                    [ZPPromptView showMessage:[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"codeMsg"]]];
                }
            } failure:^(NSError * _Nonnull error) {
                
                [ZPPromptView showMessage:@"请检查您的网络设置"];
            }];
        }
        else
        {
            [ZPPromptView showMessage:@"手机号格式错误"];
            return;
        }
    }
    else
    {
        [ZPPromptView showMessage:@"请输入手机号"];
        return;
    }
    // 开始倒计时
    [[ZPFileLoger sharedZPFileLoger] startCountDown:NSStringFromClass([self class])];
}



#pragma mark - <联系客服>
- (void)ContactCustomerService
{
    _callAlertView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([ZPCallAlertView class]) owner:self options:nil] lastObject];
    [self.callAlertView setStatus];
    _callAlertView.frame = CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height);
    __weak ZPChangePwdViewController *weakSelf = self;
    _callAlertView.cancel = ^(){ // 点击取消
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.callAlertView.concentView.xj_bottom = 1000.;
        } completion:^(BOOL finished) {
            [weakSelf.callAlertView removeFromSuperview];
        }];
    };
    _callAlertView.call = ^(){ // 点击拨打电话
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://02558115681"]];
    };
    [self.view.window addSubview:self.callAlertView];
}

#pragma mark - <核对验证码>
- (IBAction)checkValidateCode:(UIButton *)sender
{
//    if (self.flag == 100) {
//        ZPBackSetPwdViewController *backPwdVc = [[ZPBackSetPwdViewController alloc] init];
//        // 进入找回密码界面
//        [self.navigationController pushViewController:backPwdVc animated:YES];
//    }
//    else if (self.flag == 101) {
//        ZPUpdateSetPwdViewController *updatePwdVc = [[ZPUpdateSetPwdViewController alloc] init];
//        // 进入修改密码界面
//        [self.navigationController pushViewController:updatePwdVc animated:YES];
//    }

    // 判断验证码
    NSString *code = self.verificationCode.text;
    if (code.length == 0) {
        [ZPPromptView showMessage:@"请输入验证码"];
        return;
    }
    // 判断手机号格式
    NSString *mobileNum = self.phoneNumTF.text;
    if (![mobileNum zp_isValidPhoneNum]) {
        [ZPPromptView showMessage:@"手机号格式错误"];
        return;
    }
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: mobileNum ,@"mobile", code,@"validateCode",nil];
    
    [[ZPNetworking sharedZPNetworking] POST:APIPPT@"access/checkValidateCode.json" parameters:params progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        
        if ([[responseObject objectForKey:@"code"] integerValue]==200)
        {
            if ([[[responseObject objectForKey:@"result"] objectForKey:@"isOk"] boolValue])
            {
                if (self.flag == 100) {
                    ZPBackSetPwdViewController *backPwdVc = [[ZPBackSetPwdViewController alloc] init];
                    backPwdVc.mobile = self.phoneNumTF.text;
                    backPwdVc.backPwdValidateCode = self.verificationCode.text;
                    // 进入找回密码界面
                    [self.navigationController pushViewController:backPwdVc animated:YES];
                }
                else if (self.flag == 101) {
                    ZPUpdateSetPwdViewController *updatePwdVc = [[ZPUpdateSetPwdViewController alloc] init];
                    // 进入修改密码界面
                    [self.navigationController pushViewController:updatePwdVc animated:YES];
                }
            }
            else
            {
                [ZPPromptView showMessage:@"验证码错误"];
            }
        }
        else
        {
            [ZPPromptView showMessage:[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"codeMsg"]]];
        }
    } failure:^(NSError * _Nonnull error) {
        [ZPPromptView showMessage:@"请检查您的网络设置"];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
